#!/usr/bin/env bash
#
# Copyright (c) 2014 Joyent Inc., All rights reserved.
#

# Script that will overwrite ~/.ssh/authorized keys if mdata field 
# overwrite_root_akeys = OVERWRITE
# This allows for customers to update ssh keys when running this script
# By default this script is called on each boot

# load common functions and vars
. /lib/smartdc/lib_smartdc_scripts.cfg

# set overwrite_root_akeys to the string OVERWRITE 
# to overwrite root authorized_keys on reboot
overwrite_authorized_flag=$($MDATA_GET_BIN overwrite_root_akeys 2>>/dev/console)
# Convert to lowercase
overwrite_flag=$(echo $overwrite_authorized_flag | tr '[:upper:]' '[:lower:]')

if [[ "$overwrite_flag" == "overwrite" ]]; then
   lib_smartdc_info "Metadata field overwrite_root_akeys set to - \
     $overwrite_authorized_flag - Overwriting /root/.ssh/authorized_keys"
   lib_smartdc_info "Removing /root/.ssh/authorized_keys"
   rm -f /root/.ssh/authorized_keys
fi

if [[ ! -f /root/.ssh/authorized_keys ]]; then
    authorized_keys=$($MDATA_GET_BIN root_authorized_keys | \
      sed 's/\(ssh-rsa\ \)/\n\1/g' | sed 's/\(ssh-dss\ \)/\n\1/g' \
        2>>/dev/console)
    if [[ -n ${authorized_keys} ]]; then
        mkdir -p /root/.ssh
        echo -e "${authorized_keys}" > /root/.ssh/authorized_keys
        lib_smartdc_info "Creating /root/.ssh/authorized_keys with Metadata \
          field root_authorized_keys"
        chmod 700 /root/.ssh
        chmod 600 /root/.ssh/authorized_keys
        
        which restorecon &> /dev/null
        if [[ $? -eq 0 ]]; then
            restorecon -R -v /root/.ssh
        fi
    fi
fi

exit 0
